<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before>
          <span>共{{ page.total }}条数据</span>
        </template>
        <template #after>
          <el-button type="success" @click="$router.push('/import?type=user')">Excel导入</el-button>
          <el-button type="warning" @click="exportData">Excel导出</el-button>
          <el-button type="primary" :disabled="!checkPermission('add-employee')" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card>
        <el-table v-loading="loading" :data="list" border style="width: 100%">
          <el-table-column label="序号" type="index" align="center" width="50" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column width="120px" label="头像">
            <template v-slot="{ row }">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" align="center" sortable="">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>

      <!-- 添加员工 -->
      <AddEmployee :show-dialog.sync="showDialog" />

      <!-- 点击图片显示二维码 -->
      <el-dialog title="二维码" :visible="showCodeDialog" @close="showCodeDialog = false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>

      <!-- 分配角色 -->
      <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees' // 员工枚举对象
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters'
import QrCode from 'qrcode'

export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showDialog: false, // 添加员工
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null
    }
  },
  mounted() {
    this.getEmployeeList()
    this.change()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployee(id) {
      try {
        await this.$confirm('确定删除该员工吗?')
        await delEmployee(id)
        this.$message.success('删除员工成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 导出Excel
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(async excel => {
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        const data = this.formatJson(headers, rows)
        // 复杂表头
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        // 合并列
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // 导出Excel
        excel.export_json_to_excel({
          // header: ['姓名', '工资'],  表头
          // data: [['张三', 3000], ['李四', 5000]],   每一行的数据
          // filename: '员工工资表'
          filename: '员工资料表',
          header: Object.keys(headers),
          data,
          multiHeader,
          merges
        })
      })
    },
    // 对象数组转换为二维数组
    formatJson(headers, rows) {
      return rows.map(item => { // item：每一行对象
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 时间类型转换
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            // 枚举类型转换
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true
        this.$nextTick(() => {
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转换为二维码
        })
      } else {
        this.$message.warning('该用户未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      // 用await解决刚打开瞬间页面空白
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    },

    // 驼峰转下划线
    change() {
      const str = 'getAgeMap'
      const arr = str.split('')
      // console.log(arr)
      let newArr = arr.map(item => {
        if (item.charCodeAt() >= 'A'.charCodeAt() && item.charCodeAt() <= 'Z'.charCodeAt()) {
          item = '_' + item.toLowerCase()
        }
        return item
      })
      newArr = newArr.join('')
      console.log(newArr)
    }
  }
}
</script>

<style>

</style>
